<template>
  <div id="userInfoPage">
    <div class="page-header">
      <h1 class="page-title">个人中心</h1>
    </div>

    <div class="profile-container">
      <!-- 个人资料卡片 -->
      <a-card class="profile-card main-profile-card" :bordered="false">
        <div class="profile-header">
          <div class="profile-avatar-container">
            <a-avatar
              :size="120"
              :image-url="loginUserStore.loginUser.userAvatar"
              :style="{ backgroundColor: '#3370ff' }"
            >
              {{ getUserInitial(loginUserStore.loginUser.userName) }}
            </a-avatar>

            <div class="edit-avatar-btn" v-if="isEditMode">
              <a-tooltip content="更换头像">
                <a-button
                  shape="circle"
                  type="primary"
                  size="mini"
                  @click="openAvatarUploader"
                >
                  <template #icon>
                    <icon-edit />
                  </template>
                </a-button>
              </a-tooltip>
            </div>
          </div>

          <div class="profile-info">
            <h2 class="user-name">
              {{ loginUserStore.loginUser.userName || "未设置昵称" }}
            </h2>
            <div class="user-id">ID: {{ loginUserStore.loginUser.id }}</div>
            <div class="user-account">
              账号: {{ loginUserStore.loginUser.userAccount }}
            </div>
            <div class="joined-date">
              <icon-calendar />
              注册于 {{ formatDate(loginUserStore.loginUser.createTime) }}
            </div>
          </div>

          <div class="profile-actions">
            <a-button
              type="primary"
              @click="toggleEditMode"
              shape="round"
              class="edit-button"
            >
              <template #icon>
                <icon-edit v-if="!isEditMode" />
                <icon-check v-else />
              </template>
              {{ isEditMode ? "保存信息" : "编辑资料" }}
            </a-button>
          </div>
        </div>

        <a-divider />

        <!-- 个人简介 -->
        <div class="profile-bio">
          <h3 class="section-title">
            <icon-user />
            个人简介
          </h3>
          <div v-if="!isEditMode" class="bio-content">
            <p v-if="loginUserStore.loginUser.userProfile">
              {{ loginUserStore.loginUser.userProfile }}
            </p>
            <p v-else class="empty-text">这个人很懒，还没有填写个人简介...</p>
          </div>
          <a-textarea
            v-else
            v-model="user.userProfile"
            :auto-size="{ minRows: 3, maxRows: 6 }"
            placeholder="介绍一下自己吧..."
            allow-clear
            show-word-limit
            :max-length="200"
          />
        </div>
      </a-card>

      <!-- 编辑表单卡片 -->
      <a-card
        v-if="isEditMode"
        class="profile-card edit-form-card"
        :bordered="false"
      >
        <h3 class="section-title">
          <icon-settings />
          编辑个人资料
        </h3>

        <a-form :model="user" layout="vertical">
          <a-form-item field="userName" label="昵称">
            <a-input
              v-model="user.userName"
              placeholder="请输入昵称"
              allow-clear
              :max-length="20"
              show-word-limit
            />
          </a-form-item>

          <a-form-item field="userAccount" label="账号">
            <a-input
              v-model="user.userAccount"
              placeholder="请输入账号"
              allow-clear
            />
          </a-form-item>

          <a-form-item field="userAvatar" label="头像">
            <PictureUploader
              biz="user_avatar"
              :value="user.userAvatar"
              :onChange="(value) => (user.userAvatar = value)"
              ref="avatarUploaderRef"
            />
          </a-form-item>
        </a-form>

        <div class="form-actions">
          <a-space>
            <a-button @click="cancelEdit">取消</a-button>
            <a-button type="primary" @click="saveUserInfo" :loading="loading"
              >保存更改</a-button
            >
          </a-space>
        </div>
      </a-card>

      <!-- 其他信息卡片 -->
      <a-card v-else class="profile-card stats-card" :bordered="false">
        <h3 class="section-title">
          <icon-info-circle />
          账户信息
        </h3>

        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-label">账号状态</div>
            <div class="stat-value">
              <a-tag color="green">正常</a-tag>
            </div>
          </div>

          <div class="stat-item">
            <div class="stat-label">用户角色</div>
            <div class="stat-value">
              <a-tag color="blue">{{
                formatUserRole(loginUserStore.loginUser.userRole)
              }}</a-tag>
            </div>
          </div>

          <div class="stat-item">
            <div class="stat-label">注册时间</div>
            <div class="stat-value">
              {{ formatDate(loginUserStore.loginUser.createTime) }}
            </div>
          </div>

          <div class="stat-item">
            <div class="stat-label">最近登录</div>
            <div class="stat-value">
              {{ formatDate(loginUserStore.loginUser.updateTime) }}
            </div>
          </div>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import {
  getUserVoByIdUsingGet,
  updateUserUsingPost,
} from "@/api/userController.ts";
import dayjs from "dayjs";
import { useLoginUserStore } from "@/store/userStore";
import message from "@arco-design/web-vue/es/message";
import API from "@/api";
import PictureUploader from "@/components/PictureUploader.vue";
import {
  IconEdit,
  IconCheck,
  IconUser,
  IconInfoCircle,
  IconCalendar,
  IconSettings,
} from "@arco-design/web-vue/es/icon";

const isEditMode = ref(false);
const loading = ref(false);
const avatarUploaderRef = ref();

const user = reactive<API.UserVO>({
  userAccount: "",
  userAvatar: "",
  userName: "",
  userProfile: "",
});

/**
 * 格式化日期
 */
const formatDate = (date: string | undefined) => {
  if (!date) return "未知";
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

/**
 * 格式化用户角色
 */
const formatUserRole = (role: string | undefined) => {
  if (!role) return "普通用户";

  switch (role) {
    case "admin":
      return "管理员";
    case "user":
      return "普通用户";
    default:
      return role;
  }
};

/**
 * 获取用户名首字母（用于头像显示）
 */
const getUserInitial = (userName: string | undefined) => {
  if (!userName) return "?";
  return userName.charAt(0).toUpperCase();
};

// 更新信息成功后，刷新数据
const loginUserStore = useLoginUserStore();

/**
 * 打开头像上传器
 */
const openAvatarUploader = () => {
  if (avatarUploaderRef.value) {
    avatarUploaderRef.value.openModal();
  }
};

/**
 * 取消编辑
 */
const cancelEdit = () => {
  isEditMode.value = false;
};

/**
 * 保存用户信息
 */
const saveUserInfo = async () => {
  try {
    loading.value = true;
    const res = await updateUserUsingPost({
      id: loginUserStore.loginUser.id,
      ...user,
    });
    if (res.data.code === 0 && res.data.data) {
      message.success("个人信息已更新");
      loginUserStore.loginUser.userAccount = user.userAccount;
      loginUserStore.loginUser.userAvatar = user.userAvatar;
      loginUserStore.loginUser.userName = user.userName;
      loginUserStore.loginUser.userProfile = user.userProfile;
      isEditMode.value = false;
    } else {
      message.error(`更新用户信息失败，${res.data.message || "未知错误"}`);
    }
  } catch (error) {
    message.error("更新用户信息时发生错误：" + (error.message || "未知错误"));
  } finally {
    loading.value = false;
  }
};

const toggleEditMode = async () => {
  if (isEditMode.value) {
    // 保存逻辑
    saveUserInfo();
  } else {
    try {
      loading.value = true;
      const res = await getUserVoByIdUsingGet({
        id: loginUserStore.loginUser.id,
      });
      if (res.data.code === 0 && res.data.data) {
        // 将获取到的用户信息填充到 user 对象中
        user.userAccount = res.data.data.userAccount || "";
        user.userAvatar = res.data.data.userAvatar || "";
        user.userName = res.data.data.userName || "";
        user.userProfile = res.data.data.userProfile || "";
        isEditMode.value = true;
      } else {
        message.error(`获取用户信息失败，${res.data.message || "未知错误"}`);
      }
    } catch (error) {
      message.error("获取用户信息时发生错误：" + (error.message || "未知错误"));
    } finally {
      loading.value = false;
    }
  }
};
</script>

<style scoped>
#userInfoPage {
  padding: 24px;
  min-height: 100vh;
  background-color: var(--color-fill-2);
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: var(--color-text-1);
  margin: 0;
}

.profile-container {
  max-width: 900px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.profile-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.main-profile-card {
  position: relative;
}

.profile-header {
  display: flex;
  align-items: flex-start;
  padding-bottom: 24px;
  position: relative;
}

.profile-avatar-container {
  position: relative;
  margin-right: 24px;
}

.edit-avatar-btn {
  position: absolute;
  bottom: 0;
  right: 0;
}

.profile-info {
  flex: 1;
}

.user-name {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: var(--color-text-1);
}

.user-id,
.user-account {
  color: var(--color-text-3);
  margin-bottom: 4px;
  font-size: 14px;
}

.joined-date {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--color-text-3);
  font-size: 14px;
  margin-top: 8px;
}

.profile-actions {
  margin-left: auto;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  color: var(--color-text-1);
}

.profile-bio {
  margin-top: 16px;
}

.bio-content {
  background-color: var(--color-fill-2);
  border-radius: 8px;
  padding: 16px;
  color: var(--color-text-2);
  min-height: 100px;
}

.empty-text {
  color: var(--color-text-3);
  font-style: italic;
}

.edit-form-card {
  padding: 24px;
}

.stats-card {
  padding: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 24px;
}

.stat-item {
  background-color: var(--color-fill-2);
  border-radius: 8px;
  padding: 16px;
  transition: background-color 0.2s;
}

.stat-item:hover {
  background-color: var(--color-fill-3);
}

.stat-label {
  font-size: 14px;
  color: var(--color-text-3);
  margin-bottom: 8px;
}

.stat-value {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-1);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .profile-avatar-container {
    margin-right: 0;
    margin-bottom: 24px;
  }

  .profile-actions {
    margin-left: 0;
    margin-top: 24px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
